package com.haiyou.dc.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class ZKClinet {

    //连接的zk的地址及端口号配置
    private String connectString = "192.168.0.128:2181,192.168.0.129:2181,192.168.0.130:2181";
    //会话超时时间,单位毫秒
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper = null;

    //1.创建客户端
    @Before
    public void initZK() throws Exception {
        final CountDownLatch cdl = new CountDownLatch(1);
        //Watcher就是监听节点
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, event -> {
            //监听发生后触发的事
            System.out.println(event.getType() + "--" + event.getPath());
            System.out.println("连接zk服务器集群成功！");
            cdl.countDown();
        });
        cdl.await();
        log.info("------------------->{}", zooKeeper.getState());
    }

    //2.创建子节点
    @Test
    public void createNode() throws Exception {
        //参数1:创建节点的路径;
        //参数2:创建节点存储的数据;
        //3.创建节点后节点具有的权限
        //4.节点类型  持久的还是短暂的
        String create = zooKeeper.create("/yyty", "kxj".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(create);
    }

    @After
    public void closeZookeeper() throws InterruptedException {
        zooKeeper.close();
    }
}
